package com.shiroha.user.controller;

import com.shiroha.common.exception.BadRequestException;
import com.shiroha.common.pojo.dto.ChatGroupDTO;
import com.shiroha.common.utils.Result;
import com.shiroha.user.pojo.vo.ChatGroupVO;
import com.shiroha.user.service.IChatGroupService;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.util.UUID;

@RestController
@Slf4j
@AllArgsConstructor
@RequestMapping("/us/groups")
public class GroupController {

    private final IChatGroupService groupService;

    // 获取用户群组列表
    @GetMapping
    public Result<List<ChatGroupDTO>> getAllGroupsByUserId(@AuthenticationPrincipal Jwt jwt, @RequestParam(required = false) UUID userId) {
        UUID userIdOpt = Optional.ofNullable(jwt.getSubject())
                .map(UUID::fromString)
                .orElse(userId);
        return (userIdOpt != null) ? Result.success(groupService.getAllGroupsByUserId(userIdOpt)) : Result.error("userId不能为空");
    }

    // 获取群组信息
    @GetMapping("{groupId}")
    public ChatGroupDTO getGroupById(@PathVariable Long groupId) {
        return groupService.getGroupByGroupId(groupId);
    }

    // 创建群组
    @PostMapping
    public Result<String> createGroup(@AuthenticationPrincipal Jwt jwt, @Valid @RequestBody ChatGroupVO chatGroupVO) {
        ChatGroupDTO chatGroupDTO = new ChatGroupDTO();
        chatGroupDTO.setName(chatGroupVO.getName());
        chatGroupDTO.setAvatar(chatGroupVO.getAvatar());
        chatGroupDTO.setDescription(chatGroupVO.getDescription());
        chatGroupDTO.setMemberIds(chatGroupVO.getMemberIds());

        return groupService.createGroup(UUID.fromString(jwt.getSubject()), chatGroupDTO) ?
                Result.success("创建群组成功") : Result.error("创建群组失败");
    }

    // 删除群组
    @DeleteMapping
    public Result<String> deleteGroup(@AuthenticationPrincipal Jwt jwt, @RequestParam Long groupId) {
        return groupService.deleteGroup(UUID.fromString(jwt.getSubject()), groupId) ?
                Result.success("删除群组成功") : Result.error("删除群组失败");
    }
}
